package com.csrcb.config;

import com.csrcb.interceptor.OkHttpLoggerInterceptor;
import com.csrcb.interceptor.RestTemplateInterator;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @Classname RestTemplateConfig
 * @Description RestTemplate配置，内部使用okhttp请求连接，使用okhttp的请求连接池，超时等特性
 * @Date 2021/8/18 15:02
 * @Created by gangye
 */
@Configuration
public class RestTemplateConfig {
    @Value("${ok.http.connect-timeout}")
    private Integer connectTimeout;

    @Value("${ok.http.read-timeout}")
    private Integer readTimeout;

    @Value("${ok.http.write-timeout}")
    private Integer writeTimeout;

    @Value("${ok.http.max-idle-connections}")
    private Integer maxIdleConnections;

    @Value("${ok.http.keep-alive-duration}")
    private Long keepAliveDuration;

    @Bean
    public RestTemplate okHttpRestTemplate(){
        ClientHttpRequestFactory factory = okHttpClientRequestFactory();
        RestTemplate restTemplate = new RestTemplate(factory);
        // 可以添加消息转换
        //restTemplate.setMessageConverters(...);
        // 可以增加拦截器
//        restTemplate.setInterceptors(Arrays.asList(new RestTemplateInterator()));
        return restTemplate;

        /*
        //此情形用于使用纯RestTemplate的情形下使用拦截器，传递traceId等日志链路
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Arrays.asList(new RestTemplateInterator()));
        return restTemplate;
        */

    }

    @Bean
    public ClientHttpRequestFactory okHttpClientRequestFactory(){
        //使用自定义的okHttpClient
        return new OkHttp3ClientHttpRequestFactory(okHttpClient());
    }

    @Bean
    public OkHttpClient okHttpClient(){
        return new OkHttpClient.Builder()
                .connectTimeout(connectTimeout,TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout,TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(maxIdleConnections,keepAliveDuration,TimeUnit.SECONDS))
                // 设置代理
//                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
                // 拦截器
                .addInterceptor(new OkHttpLoggerInterceptor())
                .build();
    }
}
